<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="圈子名称" prop="topicName">
        <el-input
          v-model="queryParams.topicName"
          placeholder="请输入圈子名称"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="分类" prop="cateId">
        <el-select v-model="queryParams.cateId" placeholder="圈子分类" clearable style="width: 240px">
          <el-option
            v-for="item in categoryOptions"
            :key="item.cateId"
            :label="item.cateName"
            :value="item.cateId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="圈子状态" clearable style="width: 240px">
          <el-option
            v-for="dict in dict.type.sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:topic:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:topic:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:topic:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:topic:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="topicList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="圈子ID" align="center" prop="topicId" v-if="columns[0].visible" />
      <el-table-column label="圈子名称" align="center" prop="topicName" v-if="columns[1].visible" :show-overflow-tooltip="true" />
      <el-table-column label="圈子头像" align="center" prop="avatar" v-if="columns[2].visible" width="100">
        <template slot-scope="scope">
          <el-image
            style="width: 50px; height: 50px; border-radius: 50%"
            :src="scope.row.avatar"
            :preview-src-list="[scope.row.avatar]">
            <div slot="error" class="image-slot">
              <i class="el-icon-user-solid" style="font-size: 30px; line-height: 50px;"></i>
            </div>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="分类" align="center" prop="cateName" v-if="columns[3].visible" :show-overflow-tooltip="true" />
      <el-table-column label="成员数" align="center" prop="memberCount" v-if="columns[4].visible" width="80" />
      <el-table-column label="帖子数" align="center" prop="postCount" v-if="columns[5].visible" width="80" />
      <el-table-column label="创建者" align="center" prop="creatorName" v-if="columns[6].visible" :show-overflow-tooltip="true" />
      <el-table-column label="状态" align="center" v-if="columns[7].visible" width="100">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="'0'"
            :inactive-value="'1'"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" v-if="columns[8].visible" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:topic:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:topic:remove']"
          >删除</el-button>
          <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)" v-hasPermi="['system:topic:edit']">
            <el-button size="mini" type="text" icon="el-icon-d-arrow-right">更多</el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="handleMembers" icon="el-icon-user">成员管理</el-dropdown-item>
              <el-dropdown-item command="handlePosts" icon="el-icon-document">帖子管理</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改圈子对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="圈子名称" prop="topicName">
              <el-input v-model="form.topicName" placeholder="请输入圈子名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属分类" prop="cateId">
              <el-select v-model="form.cateId" placeholder="请选择所属分类">
                <el-option
                  v-for="item in categoryOptions"
                  :key="item.cateId"
                  :label="item.cateName"
                  :value="item.cateId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="圈子头像" prop="avatar">
              <el-upload
                class="avatar-uploader"
                :action="uploadImgUrl"
                :headers="headers"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload">
                <img v-if="form.avatar" :src="form.avatar" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="圈子封面" prop="coverImage">
              <el-upload
                class="cover-uploader"
                :action="uploadImgUrl"
                :headers="headers"
                :show-file-list="false"
                :on-success="handleCoverSuccess"
                :before-upload="beforeCoverUpload">
                <img v-if="form.coverImage" :src="form.coverImage" class="cover">
                <i v-else class="el-icon-plus cover-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="圈子描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入圈子描述" />
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="公开类型" prop="isPublic">
              <el-radio-group v-model="form.isPublic">
                <el-radio label="1">公开</el-radio>
                <el-radio label="0">私密</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="加入方式" prop="joinType">
              <el-radio-group v-model="form.joinType">
                <el-radio label="0">自由加入</el-radio>
                <el-radio label="1">审核加入</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in dict.type.sys_normal_disable"
                  :key="dict.value"
                  :label="dict.value"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="圈子标签" prop="tags">
          <el-input v-model="form.tags" placeholder="请输入圈子标签，多个标签用逗号分隔" />
        </el-form-item>
        <el-form-item label="圈子规则" prop="rules">
          <el-input v-model="form.rules" type="textarea" placeholder="请输入圈子规则" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 成员管理对话框 -->
    <el-dialog :title="title" :visible.sync="memberOpen" width="800px" append-to-body>
      <el-table v-loading="memberLoading" :data="memberList">
        <el-table-column label="用户ID" align="center" prop="userId" width="80" />
        <el-table-column label="用户名" align="center" prop="userName" :show-overflow-tooltip="true" />
        <el-table-column label="用户头像" align="center" prop="avatar" width="80">
          <template slot-scope="scope">
            <el-image
              style="width: 40px; height: 40px; border-radius: 50%"
              :src="scope.row.avatar"
              :preview-src-list="[scope.row.avatar]">
              <div slot="error" class="image-slot">
                <i class="el-icon-user-solid" style="font-size: 24px; line-height: 40px;"></i>
              </div>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column label="角色" align="center" prop="role" width="100">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.role === 2" type="danger">圈主</el-tag>
            <el-tag v-else-if="scope.row.role === 1" type="warning">管理员</el-tag>
            <el-tag v-else type="info">普通成员</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="禁言状态" align="center" prop="isMuted" width="100">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.isMuted === 1" type="danger">已禁言</el-tag>
            <el-tag v-else type="success">正常</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="加入时间" align="center" prop="joinTime" width="160">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.joinTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              v-if="scope.row.role !== 2"
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleRemoveMember(scope.row)"
            >移除</el-button>
            <el-button
              v-if="scope.row.role === 0"
              size="mini"
              type="text"
              icon="el-icon-s-tools"
              @click="handleSetAdmin(scope.row)"
            >设为管理员</el-button>
            <el-button
              v-if="scope.row.role === 1"
              size="mini"
              type="text"
              icon="el-icon-s-tools"
              @click="handleRemoveAdmin(scope.row)"
            >取消管理员</el-button>
            <el-button
              v-if="scope.row.isMuted === 0 && scope.row.role !== 2"
              size="mini"
              type="text"
              icon="el-icon-turn-off"
              @click="handleMuteMember(scope.row)"
            >禁言</el-button>
            <el-button
              v-if="scope.row.isMuted === 1"
              size="mini"
              type="text"
              icon="el-icon-open"
              @click="handleUnmuteMember(scope.row)"
            >解除禁言</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="memberTotal>0"
        :total="memberTotal"
        :page.sync="memberQueryParams.pageNum"
        :limit.sync="memberQueryParams.pageSize"
        @pagination="getMemberList"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="memberOpen = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listTopic, getTopic, delTopic, addTopic, updateTopic, changeTopicStatus, listTopicMembers, removeTopicMember, setMemberRole, toggleMemberMute } from "@/api/quanzi/topic";
import { listCategory } from "@/api/quanzi/category";
import { getToken } from "@/utils/auth";

export default {
  name: "Topic",
  dicts: ['sys_normal_disable'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 圈子表格数据
      topicList: [],
      // 圈子分类选项
      categoryOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        topicName: undefined,
        cateId: undefined,
        status: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        topicName: [
          { required: true, message: "圈子名称不能为空", trigger: "blur" },
          { min: 2, max: 50, message: "圈子名称长度必须介于 2 和 50 之间", trigger: "blur" }
        ],
        cateId: [
          { required: true, message: "所属分类不能为空", trigger: "change" }
        ],
        description: [
          { required: true, message: "圈子描述不能为空", trigger: "blur" },
          { max: 500, message: "圈子描述长度不能超过500个字符", trigger: "blur" }
        ]
      },
      // 列信息
      columns: [
        { key: 0, label: `圈子ID`, visible: true },
        { key: 1, label: `圈子名称`, visible: true },
        { key: 2, label: `圈子头像`, visible: true },
        { key: 3, label: `分类`, visible: true },
        { key: 4, label: `成员数`, visible: true },
        { key: 5, label: `帖子数`, visible: true },
        { key: 6, label: `创建者`, visible: true },
        { key: 7, label: `状态`, visible: true },
        { key: 8, label: `创建时间`, visible: true }
      ],
      // 上传图片地址
      uploadImgUrl: process.env.VUE_APP_BASE_API + "/common/upload",
      // 设置上传的请求头部
      headers: { Authorization: "Bearer " + getToken() },

      // 成员管理相关
      memberOpen: false,
      memberLoading: true,
      memberTotal: 0,
      memberList: [],
      currentTopicId: null,
      memberQueryParams: {
        pageNum: 1,
        pageSize: 10
      }
    };
  },
  created() {
    this.getList();
    this.getCategoryOptions();
  },
  methods: {
    /** 查询圈子列表 */
    getList() {
      this.loading = true;
      listTopic(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.topicList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询圈子分类选项 */
    getCategoryOptions() {
      listCategory().then(response => {
        this.categoryOptions = response.rows;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        topicId: undefined,
        topicName: undefined,
        cateId: undefined,
        avatar: undefined,
        coverImage: undefined,
        description: undefined,
        isPublic: "1",
        joinType: "0",
        status: "0",
        tags: undefined,
        rules: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.topicId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加圈子";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const topicId = row.topicId || this.ids;
      getTopic(topicId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改圈子";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.topicId != undefined) {
            updateTopic(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTopic(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const topicIds = row.topicId || this.ids;
      this.$modal.confirm('是否确认删除圈子编号为"' + topicIds + '"的数据项？').then(function() {
        return delTopic(topicIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/topic/export', {
        ...this.queryParams
      }, `topic_${new Date().getTime()}.xlsx`);
    },
    // 圈子状态修改
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用";
      this.$modal.confirm('确认要"' + text + '""' + row.topicName + '"圈子吗？').then(function() {
        return changeTopicStatus(row.topicId, row.status);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function() {
        row.status = row.status === "0" ? "1" : "0";
      });
    },
    // 头像上传成功处理
    handleAvatarSuccess(res, file) {
      this.form.avatar = res.url;
    },
    // 头像上传前处理
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像只能是 JPG/PNG/GIF 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    // 封面上传成功处理
    handleCoverSuccess(res, file) {
      this.form.coverImage = res.url;
    },
    // 封面上传前处理
    beforeCoverUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif';
      const isLt5M = file.size / 1024 / 1024 < 5;

      if (!isJPG) {
        this.$message.error('上传封面只能是 JPG/PNG/GIF 格式!');
      }
      if (!isLt5M) {
        this.$message.error('上传封面大小不能超过 5MB!');
      }
      return isJPG && isLt5M;
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "handleMembers":
          this.handleMembers(row);
          break;
        case "handlePosts":
          this.handlePosts(row);
          break;
        default:
          break;
      }
    },
    /** 成员管理操作 */
    handleMembers(row) {
      this.currentTopicId = row.topicId;
      this.memberOpen = true;
      this.title = row.topicName + " - 成员管理";
      this.getMemberList();
    },
    /** 查询圈子成员列表 */
    getMemberList() {
      this.memberLoading = true;
      listTopicMembers(this.currentTopicId, this.memberQueryParams).then(response => {
        this.memberList = response.rows;
        this.memberTotal = response.total;
        this.memberLoading = false;
      });
    },
    /** 移除成员 */
    handleRemoveMember(row) {
      this.$modal.confirm('确认要移除"' + row.userName + '"成员吗？').then(function() {
        return removeTopicMember(this.currentTopicId, row.userId);
      }).then(() => {
        this.getMemberList();
        this.$modal.msgSuccess("移除成功");
      }).catch(() => {});
    },
    /** 设置为管理员 */
    handleSetAdmin(row) {
      this.$modal.confirm('确认要将"' + row.userName + '"设置为管理员吗？').then(function() {
        return setMemberRole(this.currentTopicId, row.userId, 1);
      }).then(() => {
        this.getMemberList();
        this.$modal.msgSuccess("设置成功");
      }).catch(() => {});
    },
    /** 取消管理员 */
    handleRemoveAdmin(row) {
      this.$modal.confirm('确认要取消"' + row.userName + '"的管理员权限吗？').then(function() {
        return setMemberRole(this.currentTopicId, row.userId, 0);
      }).then(() => {
        this.getMemberList();
        this.$modal.msgSuccess("取消成功");
      }).catch(() => {});
    },
    /** 禁言成员 */
    handleMuteMember(row) {
      this.$modal.confirm('确认要禁言"' + row.userName + '"成员吗？').then(function() {
        return toggleMemberMute(this.currentTopicId, row.userId, 1);
      }).then(() => {
        this.getMemberList();
        this.$modal.msgSuccess("禁言成功");
      }).catch(() => {});
    },
    /** 解除禁言 */
    handleUnmuteMember(row) {
      this.$modal.confirm('确认要解除"' + row.userName + '"的禁言吗？').then(function() {
        return toggleMemberMute(this.currentTopicId, row.userId, 0);
      }).then(() => {
        this.getMemberList();
        this.$modal.msgSuccess("解除禁言成功");
      }).catch(() => {});
    },
    /** 帖子管理操作 */
    handlePosts(row) {
      this.$router.push({
        path: '/quanzi/post',
        query: { topicId: row.topicId, topicName: row.topicName }
      });
    }
  }
};
</script>

<style scoped>
.avatar-uploader .el-upload,
.cover-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover,
.cover-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
  border-radius: 50%;
}
.cover-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 200px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
.avatar {
  width: 100px;
  height: 100px;
  display: block;
  border-radius: 50%;
}
.cover {
  width: 200px;
  height: 100px;
  display: block;
}
</style>
